import React, { useState } from 'react';
import s from './style.module.less';
import { Table, Switch, Textarea, Input, Confirm, Loading, Form, Message, Dialog, Button } from '@knownsec/react-component';
import { kwCount, kwList, kwPut } from '~/API';
import { CONTENT_KEYWORD_IDX_LABEL_MAP } from '@/common/common';
import cn from 'classnames';
import i from '../../../common.module.css'
import set from 'date-fns/esm/set/index';
export default function keyword() {
  const [refe, setRef] = useState(false);
  const [loading, setLoading] = useState(true);
  const [searchInfo, setSearchInfo] = useState('');
  const [tableData, setTableData] = useState([]);
  const [selKeywords, setSelKeywords] = useState('123');
  const createForm = React.useRef();
  const columns = [
    {
      title: '类别',
      dataIndex: 'type',
      className: s.w_7,
      key: 'type',
      render: (x) => CONTENT_KEYWORD_IDX_LABEL_MAP[x] || x,
    },
    {
      title: '默认词库量',
      dataIndex: 'sys_keyword',
      className: s.center,
    },
    {
      title: '自定义词库量',
      dataIndex: 'cust_keyword',
      className: s.center,
      render: (e) => {
        return e || 0;
      },
    },
    //暂时不要
    // {
    //   title: '状态',
    //   dataIndex: 'd',
    //   render: (e, row) => {
    //     let val = e;
    //     return (
    //       <Switch
    //         value={val}
    //         onChange={(e) => {
    //           val = e.value;
    //         }}
    //       ></Switch>
    //     );
    //   },
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      className: s.w_5,
      render: (e, row) => {
        return (
          <div
            className={s.operation}
            onClick={() => {
              showDialog(row);
            }}
          >
            修改
          </div>
        );
      },
    },
  ];
  const getList = async (e = '') => {
    const data = { keyword: e };
    const list = await kwCount(data);
    setTableData(list.data);
    setLoading(false);
  };
  function validatormap(rule, value, callback) {
    const length = value.split(' ').every((e) => {
      return e.length <= 40;
    });
    if (!length) {
      callback('*敏感词超长');
    }
  }
  const [visible, setVisible] = useState(false)
  const [keyword, setKeyword] = useState('')
  const [dialogTitle, setDialogTitle] = useState('')
  const [keyList, setKeyList] = useState(null)
  const [modifyDetail, setModifyDetail] = useState(null)
  const showDialog = async (detail = {}) => {
    const keylist = await kwList(detail.type);
    const initialValue = keylist.data?.custom_keywords.join(' ');
    setModifyDetail(detail)
    setVisible(true)
    setKeyList(keylist)
    setKeyword(initialValue);
    createForm.current.setFieldsValue({ cust_keywords: initialValue })
    setDialogTitle(`${CONTENT_KEYWORD_IDX_LABEL_MAP[detail.type]}敏感词设置`)
  };
  const onSubmit = async () => {
    const res = await kwPut({ data: { cust_keywords: keyword }, id: modifyDetail.type });
    if (res.status === 'success') {
      Message.show({
        pro: true,
        type: 'success',
        message: '操作成功',
        showClose: false,
      });
    } else {
      Message.show({
        pro: true,
        type: 'error',
        message: '操作失败',
        showClose: false,
      });
    }
    setVisible(false)
    getList();
  }
  React.useMemo(() => {
    getList();
  }, []);
  React.useEffect(() => {
    document.getElementById('readonlyArea').setAttribute('readonly', true)
  }, [])

  const hideFun = () => {
    createForm.current.resetFields()
    setVisible(false)
    setKeyword('')
    setDialogTitle('')
    setKeyList(null)
    setModifyDetail(null)
  }
  return (
    <div className={s.wordMain}>
      <div className={s.tool}>
        <Input
          pro
          value={searchInfo}
          search
          autoComplete={'off'}
          clear
          onSearch={(e) => {
            getList(e.value);
          }}
          className={cn('search-button')}
          placeholder="请输入敏感词"
          maxlength={32}
          onChange={(e) => {
            if (!e.value) {
              getList(e.value);
            }
            setSearchInfo(e.value);
          }}
        />
      </div>

      <Table 
        refre={refe} 
        columns={columns} 
        className={s.table} 
        tableLoading={loading}
        loadingLabel=""
        data={tableData}></Table>
      <Dialog 
        className={s.w740} 
        title={dialogTitle} 
        visible={visible} 
        onsubmit={onSubmit} 
        cusCancel={<Button type="default" className={i.mr20} onClick={hideFun} >取消</Button>}
        onhide={hideFun}>
        <div className={s.p24}>
          <Form
            labelAlign='right'
            labelCol={{span: 3}}
            ref={createForm}
            onValuesChange={(newItem) => {
                setKeyword(newItem.cust_keywords);
            }}
          >
            <Form.Item
              label='默认词库'
            >
              <Textarea
                className={s.textarea}
                rows='7'
                id='readonlyArea'
                placeholder="请输入敏感词，按空格隔开，每个敏感词不超过40字符。"
                value={keyList?.data?.system_keywords?.join('  ')}
              />
            </Form.Item>
            <Form.Item
              label='自定义词库'
              rules={[{ validator: validatormap }]}
              name="cust_keywords"
              initialValue={keyword}
            >
              <Textarea
                className={s.textarea}
                rows='7'
                placeholder="请输入敏感词，按空格隔开，每个敏感词不超过40字符。"
              ></Textarea>
            </Form.Item>
          </Form>
        </div>
      </Dialog>
    </div>
  );
}
